package com.brainydroid.example.numerical_distance;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.client.ClientProtocolException;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.brainydroid.example.numerical_distance.ExampleNumDist;
import com.brainydroid.example.numerical_distance.tools.Text;
import com.brainydroid.example.numerical_distance.R;
import com.google.gson.Gson;

public class UIWrapperActivity extends Activity implements OnItemSelectedListener {

	/*
	 In this class
	 Presentation of the experiment 
	 - Disclaimer : 
	  	- please do your experiment correctly
	  	- accept that the result of your experiment are sent
	 - A few statistics (age)
	 - Instructions
	 - Run the experiment
	 - Get more info


	 */
	RadioButton radioDurationButton;
	RadioGroup radioDurationGroup;
	Button btnDuration;
	int duration_index;
	ArrayAdapter<CharSequence> adapter;
	String country = "";
	Button 	countrybutton;// = (Button) findViewById(R.id.button2);
	
	SeekBar bar_focus;
	SeekBar bar_calm;
	Button btnRating;

	int rating_focus;
	int rating_calm;
	
	private static String TAG = UIWrapperActivity.class.getSimpleName();
	
	private static String BS_SERVER_NAME = "http://mehho.net:5000/";
	private static String BS_EXP_APP_ID = "numerical_distance";
	
	CryptoStore cryptostore;
	Gson gson;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
 
		setContentView(R.layout.intro);	
		Button 	countrybutton ;//= (Button) findViewById(R.id.button2);

		TextView msg = (TextView)findViewById(R.id.textView1);
		msg.setText(Text.readTxt(R.raw.intro_txt,(Activity)this));   
		
		cryptostore = CryptoStore.getInstance(BS_SERVER_NAME, this.getCacheDir());
		if (! cryptostore.hasStoredKeyPairAndMaiId()) {
			try {
				cryptostore.generateAndStoreKeyPairAndMaiId();
				String serverAnswer = cryptostore.uploadPublicKey();
				Toast.makeText(UIWrapperActivity.this, serverAnswer, Toast.LENGTH_SHORT).show();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "Error generating keys or getting an mai_id or sending public key: " + e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "Error generating keys or getting an mai_id or sending public key: " + e.getMessage());
				e.printStackTrace();
			}
		
		}
		gson = new Gson();

	}


	public void Show_disclaimer(View v){

		setContentView(R.layout.disclaimer);	

		TextView msg = (TextView)findViewById(R.id.textView_disclaimer);
		msg.setText(Text.readTxt(R.raw.disclaimer_txt,(Activity)this));  


	}

	public void SpinnerButtonOnClick(View v){
		  new AlertDialog.Builder(this)
		  .setTitle("Select your country")
		  .setAdapter(adapter, new DialogInterface.OnClickListener() {

			  
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    	
		   	String[]  mTestArray  = getResources().getStringArray(R.array.countries_array);
		    	country = mTestArray[which];
			    countrybutton.setText(country);
				Toast.makeText(UIWrapperActivity.this,country, Toast.LENGTH_SHORT).show();

		      // TODO: user specific action
		      dialog.dismiss();
		    }
		  }).create().show();
	}

	public void Get_subject_info(View v){
		/*
		 * 
		 * <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.00" />
		 */
		
		setContentView(R.layout.subject_info);	
		TextView msg = (TextView)findViewById(R.id.textView2);
		msg.setText(Text.readTxt(R.raw.subject_info,this));   
		
		countrybutton = (Button) findViewById(R.id.button2);

		
		adapter = ArrayAdapter.createFromResource(this,
				R.array.countries_array, android.R.layout.simple_spinner_item);
		// Specify the layout to use when the list of choices appears
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		/* 
		 * 
		
		Spinner spinner = (Spinner) findViewById(R.id.spinner1);
		// Create an ArrayAdapter using the string array and a default spinner layout
		
		// Apply the adapter to the spinner
		spinner.setAdapter(adapter);*/


	}

	public void See_instructions(View v){

		setContentView(R.layout.instructions);	

		TextView msg = (TextView)findViewById(R.id.textViewInstructions);
		msg.setText(Text.readTxt(R.raw.instructions,this));   


	}

	public void Choose_duration(View v){

		setContentView(R.layout.duration);	

		TextView msg = (TextView)findViewById(R.id.textViewDuration);
		msg.setText(Text.readTxt(R.raw.duration_txt,this));   
		addListenerOnButton1();


	}


	public void Launch_Gdx_Experiment(View v){

		Intent intent = new Intent();
		intent.setClass(this, Numerical_distance_experiment_Activity.class);
		//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

		int exp_duration = 5*60*(duration_index+1); // time in second
		System.out.println("exp_duration - to send :"+ Integer.toString(exp_duration));


		intent.putExtra("duration", exp_duration); // passing duration as an argument

		 
		startActivity(intent);

	}


	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  // Save UI state changes to the savedInstanceState.
	  // This bundle will be passed to onCreate if the process is
	  // killed and restarted.
	  // etc.
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	  // Restore UI state from the savedInstanceState.
	  // This bundle has also been passed to onCreate.

	}

	
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		country = parent.getItemAtPosition(pos).toString();
	    countrybutton.setText(country);
		Toast.makeText(UIWrapperActivity.this,country, Toast.LENGTH_SHORT).show();

	}


	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

 @Override
 public void onRestart(){
	 super.onRestart();

		setContentView(R.layout.postexprating);	
		//addListenerOnButton1();
		  bar_focus = (SeekBar)findViewById(R.id.seekBar1); // 
		  bar_calm  = (SeekBar)findViewById(R.id.SeekBar01); // 
 }


	public void addListenerOnButton1() {

		radioDurationGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		btnDuration = (Button) findViewById(R.id.buttonDuration);

		btnDuration.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// get selected radio button from radioGroup
				int selectedId = radioDurationGroup.getCheckedRadioButtonId();

				// find the radiobutton by returned id
				radioDurationButton = (RadioButton) findViewById(selectedId);

				duration_index = radioDurationGroup.indexOfChild(radioDurationButton);

				Toast.makeText(UIWrapperActivity.this,
						radioDurationButton.getText()+" - "+Integer.toString(duration_index), Toast.LENGTH_SHORT).show();

				Choose_duration(v);		 
				See_instructions(v);

			}

		});

	}
	
	
	//-----------------------------------------------------------------------
	
	
	public void See_highscores(View v){
		setContentView(R.layout.highscores);	
	}

	public void See_results(View v){
		
//	Intent  intent = new Intent(this, GeneratedChartDemo.class);
//	Intent  intent = new Intent(this, generatechart.class);
//   startActivity(intent);
	}

	public void See_ratings(View v){
		setContentView(R.layout.postexprating);	
		addListenerOnButton1();

		  bar_focus = (SeekBar)findViewById(R.id.seekBar1); // 
		  bar_calm  = (SeekBar)findViewById(R.id.SeekBar01); // 

	}
	public void See_thanks(View v){
		setContentView(R.layout.thanks);	
		TextView msg = (TextView)findViewById(R.id.textViewThanks);
		msg.setText(Text.readTxt(R.raw.thanks,(Activity)this));   

	}


	public void Click_Exit(View v){
		System.exit(0);
	}

	  public void addListenerOnButton() {
			 
		btnRating = (Button) findViewById(R.id.Button01);
	 
		btnRating.setOnClickListener(new OnClickListener() {
	 
			@Override
			public void onClick(View v) {
	 
				   rating_focus = bar_focus.getProgress();	
			  rating_calm = bar_calm.getProgress();
			  See_results(v);
	 
			}
	 
		});
	 
	  }


	  public void sendData(View v) throws IOException{
		  
		  Result result = sd2data.loaddata();
		  String jsonData = gson.toJson(result);
		  String serverAnswer = cryptostore.signAndUploadData(BS_EXP_APP_ID, jsonData);
		  Toast.makeText(UIWrapperActivity.this, serverAnswer, Toast.LENGTH_SHORT).show();
		  
	  }
	  

}



